<?php
namespace app\common\model;

class Message extends BaseModel{
	public $status_desc = '';
	public $ask_user_id = 0;
	public $send_user_id = 0;

	/**
	 * 添加消息
	 * @param integer $send_user_id 发送者用户ID，0系统发送
	 * @param [type]  $to_user_id   接收用户ID
	 * @param string  $title        消息标题
	 * @param string  $content      消息内容
	 * @param string  $msg_type     消息类型：系统消息system、订单消息order、账单消息account、服务消息todo
	 * @param string  $content_type 内容类型：text
	 * @param string  $relation_id  关联ID，如提现ID、订单号
	 */
	public function add_msg($send_user_id = 0, $to_user_id, $title = '', $content = '', $msg_type = 'system', $content_type = 'text', $relation_id = ''){
		if(!$to_user_id){
			return false;
		}
		$data['user_id']      = $to_user_id;
		$data['title']        = $title ? $title : '';
		$data['content']      = $content;
		$data['msg_type']     = $msg_type;
		$data['content_type'] = $content_type;
		$data['relation_id']  = $relation_id ? $relation_id : 0;
		$data['is_send_sms']  = $this->is_send_sms ? 1 : 0;
		$data['create_time']  = time();

		// 添加系统消息记录，
		$log = $data;
		$log['is_push']       = 1;// 是否进行推送
		$log['user_id']       = $to_user_id;
		$log['mobiles']       = $this->mobiles ? $this->mobiles : '';
		$log['status_desc']   = $this->status_desc ? $this->status_desc : '';
		$log['tpl_name']      = $this->tpl_name ? $this->tpl_name : '';
		$log['tpl_key']       = $this->tpl_key ? $this->tpl_key : '';
		$log['is_weixin_msg'] = $this->is_weixin_msg ? 1 : 0;
		$log['send_user_id']  = $send_user_id ? $send_user_id : 0;
		db('MessageLog')->insert($log);
		unset($log);
		$data['send_user_id'] = $send_user_id;

		$where['user_id']      = $to_user_id;
		$where['send_user_id'] = $send_user_id;
		$where['msg_type']     = $msg_type;
		if($this->where($where)->count()){
			//更新消息数量
			$data['unread_num'] = array('exp', 'unread_num+1');
			$this->update($data, $where, true);
			//自己消息列表也一起更新
			if($send_user_id != 0 && $send_user_id != $to_user_id){
				$where['user_id']      = $send_user_id;
				$where['send_user_id'] = $to_user_id;
				unset($data['user_id'], $data['send_user_id'], $data['unread_num'], $data['is_sms_tiped']);
				$this->update($data, $where, true);
			}
		}else{
			$data['unread_num']    = 1;
			$data['is_allow_send'] = 1;
			$this->create($data, true);
			//自己消息列表也一起更新
			if($send_user_id != 0 && $send_user_id != $to_user_id){
				$data['user_id']       = $send_user_id;
				$data['send_user_id']  = $to_user_id;
				$data['is_allow_send'] = 0;
				unset($data['unread_num'], $data['is_sms_tiped']);
				$this->create($data, true);
			}
		}
	}
	/**
	 * 系统消息推送
	 * @param  [type] $key [description]
	 * @return [type]      [description]
	 */
	public function system_msg_push($to_user_id = '', $key = ''){
		$system_push_tpl = C('system_push_tpl');
		$tpl = $system_push_tpl[$key];
		$content     = $tpl['content'];
		$is_send_sms = $tpl['is_send_sms'];

		if(!$to_user_id || !$content){
			return;
		}
		// 消息标题
		$title  = '系统消息';
		//手机号
		$user_name = D('User')->get_user_name($to_user_id);
		$mobile    = D('User')->get_user_mobile($to_user_id);

		//要被替换字段
		$search = array(
			'{$user_name}',
			'{$mobile}',
			'{$user_id}',
		);
		//替换后字段
		$replace = array(
			$user_name,
			$mobile,
			$to_user_id,
		);
		//替换后内容(给对方)
		$content = str_replace($search, $replace, $content);

		//添加记录
		$this->is_send_sms   = $is_send_sms;// 是否发送短信
		$this->mobiles       = $mobile;// 短信接收手机号多个以逗号分隔
		$this->tpl_name      = 'system_push_tpl';
		$this->tpl_key       = $key;
		$this->is_weixin_msg = $tpl['weixin_tpl_id'] ? 1 : 0;
		$this->add_msg(0, $to_user_id, $title, $content, 'system', 'text');
	}

	/**
	 * 回答推送
	 * @param  [type] $answer_id 回答ID
	 * @param  [type] $key       推送模板KEY
	 */
	public function ask_answer_push($answer_id = 0, $key = '', $send_user_id = 0){
		$push_tpl    = config('message.ask_answer_tpl');
		$tpl         = $push_tpl[$key];
		$content     = $tpl['content'];
		$is_send_sms = $tpl['is_send_sms'];

		$title       = $tpl['title'];
		$title       = $title ? $title : '回答消息';
		$msg_type    = $tpl['msg_type'];
		$msg_type    = $msg_type ? $msg_type : 'ask_answer';

		if(!$answer_id || !$content){
			return false;
		}

		//模板替换
		$info  = $this->ask_answer_replace($answer_id, $content);
		//替换后内容(给对方)
		$content        = $info['content'];
		$to_mobile      = $info['mobile'];
		//接收用户ID
		$to_user_id     = $info['ask_user_id'];
		$answer_user_id = $info['answer_user_id'];
		$ask_id         = $info['ask_id'];

		//添加记录
		$this->is_send_sms   = $is_send_sms;// 是否发送短信
		$this->mobiles       = $to_mobile;// 短信接收手机号多个以逗号分隔
		$this->tpl_name      = 'ask_answer_tpl';
		$this->tpl_key       = $key;
		$this->is_weixin_msg = $tpl['weixin_tpl_id'] ? 1 : 0;
		if($send_user_id != $to_user_id){
			$this->add_msg($send_user_id, $to_user_id, $title, $content, $msg_type, 'text', $answer_id);
		}
		if($key == 'praise' && $answer_user_id != $send_user_id && $to_user_id != $answer_user_id){
			$this->add_msg($send_user_id, $answer_user_id, $title, $content, $msg_type, 'text', $answer_id);
		}
		// 关注用户也收到相应消息
		if($key == 'answer_submit'){
			$user_id_arr = model('User')->get_fav_user_ids($ask_id, 'ask_focus', true);
			foreach ($user_id_arr as $to_user_id) {
				if($to_user_id != $info['ask_user_id'] && $to_user_id != $send_user_id){
 					$this->mobiles = model('User')->get_user_mobile($to_user_id);
					$this->add_msg($send_user_id, $to_user_id, $title, $content, $msg_type, 'text', $answer_id);
				}
			}
		}
		
	}
	/**
	 * 回答推送模板替换
	 * @param  string $answer_id    订单号
	 * @param  string $content      替换内容
	 */
	public function ask_answer_replace($answer_id = '', $tpl_content = ''){

		$info = model('AskAnswer')->where(['answer_id' => $answer_id])->find();

		$ask_title     = $info['ask_title'];
		$praise_num    = $info['praise_num'];
		$comment_num   = $info['comment_num'];
		$is_best       = $info['is_best'];
		$best_reward   = $info['best_reward'];
		$content       = $info['content'];
		$datetime_desc = date('Y-m-d H:i:s', $info['create_time']);
		$mobile        = $this->getUserMobileAttr($info['user_id']);
		$ask_mobile    = $this->getUserMobileAttr($info['ask_user_id']);

		//要被替换字段
		$search = array(
			'{$ask_title}',
			'{$praise_num}',
			'{$comment_num}',
			'{$mobile}',
			'{$ask_mobile}',
			'{$best_reward}',
			'{$datetime_desc}',
		);
		//替换后字段
		$replace = array(
			$ask_title,
			$praise_num,
			$comment_num,
			$mobile,
			$ask_mobile,
			$best_reward,
			$datetime_desc,
		);
		
		$data['content']        = str_replace($search, $replace, $tpl_content);
		$data['answer_user_id'] = $info['user_id'];
		$data['ask_user_id']    = $info['ask_user_id'];
		$data['ask_id']         = $info['ask_id'];
		$data['search']         = $search;
		$data['replace']        = $replace;
		$data['answer_id']      = $answer_id;
		$data['mobile']         = $ask_mobile ? $ask_mobile : '';

		return $data;
	}
	/**
	 * 评论推送
	 * @param  [type] $comment_id 回答ID
	 * @param  [type] $key       推送模板KEY
	 */
	public function comment_push($comment_id, $key, $send_user_id = 0){
		$push_tpl    = config('message.comment_tpl');
		$tpl         = $push_tpl[$key];
		$content     = $tpl['content'];
		$is_send_sms = $tpl['is_send_sms'];

		$title       = $tpl['title'];
		$title       = $title ? $title : '评论消息';
		$msg_type    = $tpl['msg_type'];
		$msg_type    = $msg_type ? $msg_type : 'comment';

		if(!$comment_id || !$content){
			return false;
		}

		// 模板替换
		$info  = $this->comment_replace($comment_id, $content);
		// 替换后内容(给对方)
		$content        = $info['content'];
		$to_mobile      = $info['mobile'];
		// 问题用户ID
		$ask_user_id    = $info['ask_user_id'];
		// 回复用户ID
		$reply_user_id  = $info['reply_user_id'];
		// 回答用户ID
		$answer_user_id = $info['answer_user_id'];

		//添加记录
		$this->is_send_sms   = $is_send_sms;// 是否发送短信
		$this->mobiles       = $to_mobile;// 短信接收手机号多个以逗号分隔
		$this->tpl_name      = 'comment_tpl';
		$this->tpl_key       = $key;
		$this->is_weixin_msg = $tpl['weixin_tpl_id'] ? 1 : 0;
		// 评论消息
		if($key != 'answer_reply' && $send_user_id != $ask_user_id){
			$this->add_msg($send_user_id, $ask_user_id, $title, $content, $msg_type, 'text', $comment_id);
		}
		// 回答用户评论消息
		if($key != 'answer_reply' && $answer_user_id != $send_user_id && $ask_user_id != $answer_user_id){
			$this->add_msg($send_user_id, $answer_user_id, $title, $content, $msg_type, 'text', $comment_id);
		}
		// 回复消息
		if($reply_user_id && $send_user_id != $reply_user_id){
			$this->add_msg($send_user_id, $reply_user_id, $title, $content, 'to_me_comment', 'text', $comment_id);
		}
	}
	/**
	 * TODO消息模板替换
	 * @param  string $comment_id    订单号
	 * @param  string $content      替换内容
	 */
	public function comment_replace($comment_id = '', $tpl_content = ''){

		$info = model('Comment')->where(['comment_id' => $comment_id])->find();
		$content        = $info['content'];
		$datetime_desc  = date('Y-m-d H:i:s', $info['create_time']);
		$ask_user_id    = 0;
		$answer_user_id = 0;
		switch ($info['module']) {
			case 'ask':
				$ask_id = $info['object_id'];
				$ask    = db('Ask')->field('user_id,title')->where(['ask_id' => $ask_id])->find();
				$ask_user_id = $ask['user_id'];
				$ask_title   = $ask['title'];
				break;
			
			case 'ask_answer':
				$answer         = db('AskAnswer')->field('user_id,ask_user_id,ask_id')->where(['answer_id' => $info['object_id']])->find();
				$ask_id         = $answer['ask_id'];
				$ask_user_id    = $answer['ask_user_id'];
				$answer_user_id = $answer['user_id'];
				$ask_title      = db('Ask')->where(['ask_id' => $ask_id])->value('title');
				break;
			
			default:
				# code...
				break;
		}
		$mobile = $this->getUserMobileAttr($ask_user_id);
		//要被替换字段
		$search = array(
			'{$ask_id}',
			'{$ask_title}',
			'{$mobile}',
			'{$content}',
			'{$datetime_desc}',
		);
		//替换后字段
		$replace = array(
			$ask_id,
			$ask_title,
			$mobile,
			$content,
			$datetime_desc,
		);
		
		$data['content']        = str_replace($search, $replace, $tpl_content);
		$data['reply_user_id']  = $info['reply_user_id'];
		$data['self_user_id']   = $info['user_id'];
		$data['ask_user_id']    = $ask_user_id;
		$data['search']         = $search;
		$data['replace']        = $replace;
		$data['ask_id']         = $ask_id;
		$data['comment_id']     = $comment_id;
		$data['answer_user_id'] = $answer_user_id;
		$data['mobile']         = $mobile;

		return $data;
	}
	/**
	 * 问题推送
	 * @param  [type] $ask_id 回答ID
	 * @param  [type] $key       推送模板KEY
	 */
	public function ask_push($ask_id, $key, $send_user_id = 0){
		$push_tpl    = config('message.ask_tpl');
		$tpl         = $push_tpl[$key];
		$content     = $tpl['content'];
		$is_send_sms = $tpl['is_send_sms'];

		$title       = $tpl['title'];
		$title       = $title ? $title : '问题消息';
		$msg_type    = $tpl['msg_type'];
		$msg_type    = $msg_type ? $msg_type : 'ask';

		if(!$ask_id || !$content){
			return false;
		}

		// 模板替换
		$info  = $this->ask_replace($ask_id, $content);

		// 替换后内容(给对方)
		$content       = $info['content'];
		$to_mobile     = $info['mobile'];
		// 问题用户ID
		$ask_user_id   = $info['ask_user_id'];

		//添加记录
		$this->is_send_sms   = $is_send_sms;// 是否发送短信
		$this->mobiles       = $to_mobile;// 短信接收手机号多个以逗号分隔
		$this->tpl_name      = 'ask_tpl';
		$this->tpl_key       = $key;
		$this->is_weixin_msg = $tpl['weixin_tpl_id'] ? 1 : 0;
		if($send_user_id != $ask_user_id){
			$this->add_msg($send_user_id, $ask_user_id, $title, $content, $msg_type, 'text', $ask_id);
		}
	}
	/**
	 * 问题消息模板替换
	 * @param  string $ask_id    订单号
	 * @param  string $content      替换内容
	 */
	public function ask_replace($ask_id = '', $tpl_content = ''){

		$info = model('Ask')->where(['ask_id' => $ask_id])->find();
		$title         = $info['title'];
		$content       = $info['content'];
		$datetime_desc = date('Y-m-d H:i:s', $info['create_time']);
		$ask_user_id   = $info['user_id'];
		$mobile        = $this->getUserMobileAttr($ask_user_id);
		//要被替换字段
		$search = array(
			'{$title}',
			'{$mobile}',
			'{$content}',
			'{$datetime_desc}',
		);
		//替换后字段
		$replace = array(
			$title,
			$mobile,
			$content,
			$datetime_desc,
		);
		
		$data['content']     = str_replace($search, $replace, $tpl_content);
		$data['ask_user_id'] = $ask_user_id;
		$data['search']      = $search;
		$data['replace']     = $replace;
		$data['mobile']      = $mobile;

		return $data;
	}
	/**
	 * 微信消息模板数据
	 * @param  string $tpl_name    模板名称
	 * @param  string $tpl_key     模板KEY
	 * @param  string $relation_id 数据ID
	 */
	public function weixin_tpl_data($tpl_name = '', $tpl_key = '', $relation_id = ''){
		if(!$tpl_name || !$tpl_key || !$relation_id){
			return false;
		}
		$tpl_info = config('message.' . $tpl_name);;
		$tpl             = $tpl_info[$tpl_key];
		$weixin_tpl_id   = $tpl['weixin_tpl_id'];
		$weixin_key_name = $tpl['weixin_key_name'];
		$weixin_first    = $tpl['weixin_first'];
		$weixin_remark   = $tpl['weixin_remark'];
		$weixin_open_url = $tpl['weixin_open_url'];

		switch ($tpl_name) {
			case 'order_push_tpl':
				$return_data = $this->order_tpl_replace($relation_id);
				$url_params  = 'order_sn=' . $relation_id;
				if($tpl_key == 'dispatch'){
					$url_params  = 'service_no=' . $return_data['service_no'];
				}
				break;
			
			case 'todo_push_tpl':
				$return_data = $this->todo_tpl_replace($relation_id);
				$url_params  = 'service_no=' . $return_data['service_no'];
				break;
			case 'bill_push_tpl':
				$return_data = $this->bill_push_tpl($relation_id);
				$url_params  = '';
				break;
			
			default:
				# code...
				break;
		}
		if(!$return_data){
			return false;
		}
		$search  = $return_data['search'];
		$replace = $return_data['replace'];
		foreach ($search as $key => $value) {
			$new_data[$value] = $replace[$key];
		}
		$replace_data = array();
		foreach ($weixin_key_name as $key => $value) {
			$tpl_val = $new_data[$value];
			$tpl_val = $tpl_val ? $tpl_val : '';
			$replace_data[$key] = array('value' => $tpl_val, 'color' => '#173177');
		}
		// 前半部分替换
		$first = str_replace($search, $replace, $weixin_first);
		$replace_data['first']  = array('value' => $first, 'color' => '#173177');
		// 后半部分替换
		$remark = str_replace($search, $replace, $weixin_remark);
		$replace_data['remark'] = array('value' => $remark, 'color' => '#173177');

		$data['template_id']  = $weixin_tpl_id;
		$data['replace_data'] = $replace_data;
		$data['open_url']     = conf('wap_url') . $weixin_open_url . '/?is_auto_login=1&' . $url_params;

		return $data;
	}

	/**
	 * 获取用户未读消息数据
	 * @param  integer $user_id [description]
	 * @return [type]           [description]
	 */
	public function getUserMessageUnReadNum($user_id = 0){
		if(!$user_id){
			return 0;
		}
		$number = $this->where(['user_id' => $user_id])->sum('unread_num');

		return $number ? $number : 0;
	}
	/**
	 * 设置用户消息为已读
	 * @param integer $user_id [description]
	 */
	public function setUserMessageReaded($user_id = 0){
		if(!$user_id){
			return false;
		}
		$this->where(['user_id' => $user_id])->update(['unread_num' => 0]);

		return true;
	}

}